package me.fung.wubi.worker.printer

import me.fung.wubi.base.define.table.CodeTable
import me.fung.wubi.base.define.value.CodeList
import me.fung.wubi.base.define.value.toCode
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class LimeTextPrinter(
    override var outPutFile: File
) : BaseTablePrinter() {
    override fun buildContent(table: CodeTable, config: PrintConfig): String {
        return header() + limeContent(table)
    }

    private fun header(): String = buildString {
        append("[CODETABLEHEADER]\r\n")
        append("Name=五笔工厂98词库${SimpleDateFormat("yyMMddHHmm").format(Date())}\r\n")
        val version = "1.0." + SimpleDateFormat("yyMMdd").format(Date())
        append("Version=$version\r\n")
        append("Author=五笔工厂\r\n")
        append("CodeScheme=五笔字型98版\r\n")
        append("CodeLength=4\r\n")
        append("BWCodeLength=0\r\n")
        append("SpecialPrefix=zz\r\n")
        append("PhraseRule=1\r\n")
    }

    private fun limeContent(table: CodeTable): String = buildString {
        append("[CODETABLE]\r\n")
        CodeList.value.forEach { codeValue: String ->
            val item = table.codeItemOrNull(codeValue.toCode())
            if (item?.isNotEmpty() == true) {
                for (i in 0 until item.size) {
                    append(codeValue)
                    append("\t")
                    append(item[i].value)
                    append("\t")
                    append((kotlin.math.max(1000 - i, 1)).toString())
                    append("\r\n")
                }
            }
        }
    }

}